package com.bjpowernode.future;

import com.bjpowernode.util.ThreadUtils;

import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName MyFuture
 *
 * @Author Cat
 */
public class MyFuture {

    //基于Executor框架实现线程池
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            8,
            16,
            15,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(15),
            Executors.defaultThreadFactory(),
            //Executors.privilegedThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    //业务service，处理业务的
    private ArchiveSearchService archiveSearchService = new ArchiveSearchService();

    public void search(final String keyword) {
        Future<List<String>> future = threadPoolExecutor.submit(new Callable<List<String>>() {
            @Override
            public List<String> call() {
                ThreadUtils.sleep(2);
                return archiveSearchService.search(keyword);
            }
        });
        //doOtherThings(); // 当上面正在搜索的时候，此处也可以做点别的事情
       try {
           System.out.println(future.isDone()); //false

           //List<String> result = future.get(); // 从future中获取结果

           List<String> result = future.get(3000, TimeUnit.MILLISECONDS);
           /*
           System.out.println(future.isDone()); //true
           System.out.println(future.cancel(true));
           System.out.println("isCancelled: " + future.isCancelled());
           */
           System.out.println(result); // 打印任务执行后的结果
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
           throw new RuntimeException(e);
       }
    }

    public void searchNull(final String keyword) {
        Future<List<String>> future = threadPoolExecutor.submit(new Callable<List<String>>() {
            @Override
            public List<String> call() {
                ThreadUtils.sleep(2);
                return archiveSearchService.searchNull(keyword);
            }
        });
        try {
            List<String> result = future.get();
            System.out.println(result); // 打印任务执行后的结果
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * main方法测试运行
     *
     * @param args
     */
    public static void main(String[] args) {
        MyFuture myFuture = new MyFuture();
        myFuture.search("科技");

        //关闭线程池
        threadPoolExecutor.shutdown();
    }
}